from sqlalchemy import *
from django.db.models.fields import *
from utils import update_metaclass

FIELD_TYPES = {
    'AutoField':                    Integer,
    'BooleanField':                 Boolean,
    'CharField':                    String,
    'CommaSeparatedIntegerField':   String,
    'DateField':                    Date,
    'DateTimeField':                DateTime,
    'FileField':                    (String, 100),
    'FilePathField':                (String, 100),
    'FloatField':                   Float,
    'ImageField':                   (String, 100),
    'IntegerField':                 Integer,
    'IPAddressField':               (CHAR, 100),
    'ManyToManyField':              None,
    'NullBooleanField':             Boolean,
    'OneToOneField':                Integer,
    'PhoneNumberField':             (String, 20),
    'PositiveIntegerField':         Integer,
    'PositiveSmallIntegerField':    SmallInteger,
    'SlugField':                    String,
    'SmallIntegerField':            SmallInteger,
    'TextField':                    TEXT,
    'TimeField':                    Time,
    'USStateField':                 (String, 2),
}


class Field(object):
    __metaclass__ = update_metaclass
    def __init__(self, deferred=False, **kwargs):
        self.deferred = deferred
        getattr(self, 'old___init__')(**kwargs)

    def setup_sa_column(self):
        kwargs = dict(key=self.column, nullable=self.null,
                index=self.db_index, unique=self.unique)
        kwargs.update(self.sa_column_kwargs())
        self.sa_column = Column(self.name, self.sa_column_type(), 
                *self.sa_column_args(),
                **kwargs)

    def sa_column_type(self):
        column_type = FIELD_TYPES[type(self).__name__]
        if isinstance(column_type, tuple):
            column_type = tuple[0](*tuple[1:])
        return column_type

    def sa_column_args(self):
        return tuple()

    def sa_column_kwargs(self):
        return dict()

    def set_attributes_from_name(self, name):
        self.old_set_attributes_from_name(name)
        self.setup_sa_column()

class AutoField(object):
    __metaclass__ = update_metaclass
    def sa_column_kwargs(self):
        kwargs = dict(primary_key=True)
        base = super(AutoField, self).sa_column_kwargs()
        base.update(kwargs)
        return base

class CharField(object):
    __metaclass__ = update_metaclass
    def sa_column_type(self):
        return FIELD_TYPES[type(self).__name__](length=self.maxlength)
